import { ref, watch } from 'vue';
import { REQU, SignInInfoInvalidCondPair, toFormData, useResp } from '@/net/requ.js';
import { UserOpGte } from '../op-perms.js';
import { message } from 'ant-design-vue';
import { classes, editingLayers, keydownCondPairs, labelColorMap, trfNewline } from '../common.js';
import { UUID } from '@/util/rnd.js';
import { Layer, lastSelectIndex } from './use-layer.js';

export const SerialNumClassName = auditStatus => ({ 1: 'pass', 2: 'reject' })[auditStatus];

export const fileContents = ref([]);

/**
 * @param {import('../@types/index.js').Layer} o
 * @returns {import('../@types/index.js').Layer}
 */
const fromStorable = index => {
  const label = classes.value[index];
  const color = labelColorMap.value[label];

  return R.mergeRight(Layer(), { label, index, color, id: UUID() });
};

/** @returns {import('../@types/index.js').PicStateItem} */
export const PicStateItem = (file, index) => Object.assign(file, {
  assignedFileId: file.id,
  assignedLabels: file.assignedLabels ? JSON.parse(file.assignedLabels).map(fromStorable) : [],
  comments: []/* (file.note ? JSON.parse(file.note) : []).map(commentAssignProps) */,
});

export const picState = ref({
  i: 0,
  /** @type {import('../@types/index.js').PicStateItem[]} */
  list: [
    { assignedLabels: [] }
  ],
  get no() {
    return this.i + 1;
  },
  get prev() {
    return this.list[this.i - 1];
  },
  get curr() {
    return this.list[this.i];
  },
  /** @type {import('../@types/index.js').Layer[]} */
  get layers() {
    return this.curr?.assignedLabels ?? [];
  },
  set layers(v) {
    this.curr && (this.curr.assignedLabels = v);
  },
  /** @type {import('../@types/index.js').Comment[]} */
  get comments() {
    return this.curr?.comments ?? []
  },
  set comments(v) {
    this.curr && (this.curr.comments = v);
  },
});

export function saveFile(picStateItem) {
  return REQU('/api/task/assignedFileSave', {
    method: 'POST',
    body: toFormData({
      auditStatus: UserOpGte('审核') ? picStateItem.auditStatus : null,
      assignedFileId: picStateItem.assignedFileId,
      assignedLabels: JSON.stringify(
        picStateItem.assignedLabels.map(R.prop('index'))
      ),
    })
  })
  .then(useResp({
    succ: result => result,
    fail: R.cond([
      SignInInfoInvalidCondPair(),
      [() => true, result => message.error(result.message || '保存失败')],
    ]),
  }))
}

watch(
  () => picState.value.i,
  (newVal, oldVal) => {
    editingLayers.value = [];
    lastSelectIndex.value = -1;

    document.querySelector('#label-area > p').innerHTML = trfNewline(fileContents.value[picState.value.i])

    // 更新 localStorage
    const pkgInfo = JSON.parse(localStorage.getItem('pkgInfo'));
    pkgInfo.file = picState.value.curr.assignedFileId;
    localStorage.setItem('pkgInfo', JSON.stringify(pkgInfo));
  }
);

export default function useTask() {
  keydownCondPairs.push(
    [event => 's' == event.key && event.ctrlKey, () => saveFile(picState.value.curr)],
  );
}
